package com.combetter.changxing.net;

import com.google.gson.Gson;
import com.combetter.changxing.util.LogUtil;
import com.combetter.changxing.viewmodel.base.BaseRefreshViewModel;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Mark.fan on 2018/5/11.
 */

public abstract class HttpServiceCallback<T> implements Callback<T> {

    /**
     * 控制下拉刷新
     */
    private BaseRefreshViewModel mRefreshViewModel;

    public HttpServiceCallback() {
        this(null);
    }

    /**
     * 控制下拉刷新
     * @param refreshViewModel
     */
    public HttpServiceCallback(BaseRefreshViewModel refreshViewModel) {
        mRefreshViewModel = refreshViewModel;
        onHttpStart();
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        T result = response.body();
        if (result == null) {
            onHttpFaile(response.code(), "网络错误，请稍后再试");
        } else {
            onHttpSuccess(result, response.message());
            LogUtil.e(new Gson().toJson(result));
//            if (result.getCode() == HttpStatus.RESULT_OK) {
//                onHttpSuccess(result.getData(), result.getMsg());
//            } else {
//                onHttpFaile(result.getCode(), result.getMsg());
//            }
        }
        onHttpComplete();
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        t.printStackTrace();
        onHttpError();
        onHttpComplete();
    }
    /**
     * 通常是服务器出错返回了非约定格式
     * @param code
     * @param msg
     */
    public  void onHttpFaile(int code, String msg){}

    /**
     * 返回成功
     * @param data
     * @param msg
     */
    public abstract void onHttpSuccess(T data, String msg);

    /**
     * 网络异常或json解析失败
     */
    public void onHttpError(){}

    /**
     * 数据请求结束
     */
    public void onHttpComplete(){
        if (mRefreshViewModel != null) {
            mRefreshViewModel.setRefreshing(false);
            mRefreshViewModel = null;
        }
    }

    /**
     * 请求开始
     */
    public void onHttpStart(){
        if (mRefreshViewModel != null) {
            mRefreshViewModel.setRefreshing(true);
        }
    }
}
